package com.vertx.data.druid;


import com.alibaba.druid.pool.DruidDataSource;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.spi.DataSourceProvider;

import javax.sql.DataSource;
import java.sql.SQLException;

/***
 * 改用Druid链接池
 */
public class DruidDataSourceProvider implements DataSourceProvider {

    @Override
    public int maximumPoolSize(DataSource dataSource, JsonObject config) throws SQLException {
        if (dataSource instanceof DruidDataSource) {
            Integer val = config.getInteger("max_active");
            if (val == null) {
                val =8;//默认8个
            }
            return val.intValue();
        } else {
            return -1;
        }
    }

    @Override
    public DataSource getDataSource(JsonObject config) throws SQLException {
        String url = config.getString("url");
        if (url == null) {
            throw new NullPointerException("url cannot be null");
        } else {
            String driverClass = config.getString("driver_class");
            String user = config.getString("user");
            String password = config.getString("password");
            Integer initialSize=config.getInteger("initial_size");
            Integer maxActive=config.getInteger("max_active");
            Integer minIdle=config.getInteger("min_idle");
            Long maxWait=config.getLong("max_wait");
            DruidDataSource drui=new DruidDataSource();
            drui.setUrl(url);

            drui.setDriverClassName(driverClass);

            if (null!=user) {
                drui.setUsername(user);
            }
            if (null!=password) {
                drui.setPassword(password);
            }
            if(null!=initialSize){
                drui.setInitialSize(initialSize);
            }
            if(null!=maxActive){
                drui.setMaxActive(maxActive);
            }
            if (null!=minIdle) {
                drui.setMinIdle(minIdle);
            }
            if(null!=maxWait){
                drui.setMaxWait(maxWait);
            }
            return drui;
        }
    }

    @Override
    public void close(DataSource dataSource) throws SQLException {
        if (dataSource instanceof DruidDataSource) {
            ((DruidDataSource)dataSource).close();
        }
    }

}